
innerapp.controller('gateway_watcher_Ctrl', ['$scope', '$timeout', '$http', '$cookies', '$route', '$location',
function ($scope, $timeout, $http, $cookies,$route,$location) {
    var userName = $cookies.get("userName");
    var serverIP = "127.0.0.1";
    var pubTopic = "GW001-highde-gateway";
    var subTopic = "GW001-highde-cloud";

    var timeTick = 3000;
    var timer = function () {
        if ($scope.currentGateway == null)
            return $timeout(timer, timeTick);
        $http.get("/Service/gsw/getFrame/?uuid=" + $scope.currentGateway.UUID + "&user=" + userName)
            .then(function (result) {                
                if ($scope.pauseFlag) {
                    return;
                }
                if(result.data != null && Object.prototype.toString.call(result.data) === '[object Array]')
                    if(result.data.length > 0){
                        var now = new Date();
                        var nowStr = "" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds()
                        console.log(result.data)
                        for (let index = 0; index < result.data.length; index++) {
                            const element = result.data[index];
                            directTemp = "rx";
                            if(element.topic.indexOf("-cloud") > -1 || element.topic.indexOf("-p") > -1 || element.topic.indexOf("-pub") > -1)
                                directTemp = "tx"
                            $scope.frames.unshift({
                                direct: directTemp,
                                time: nowStr,
                                frame: element.value
                            });     
                            if ($scope.frames.length > $scope.totCount) {
                                $scope.frames.splice($scope.totCount, $scope.frames.length - $scope.totCount)
                            }                   
                        }
                    }
            });
        $timeout(timer, timeTick);
    };
    if (typeof (userName) != "string") {
        userName = "";
        alert("用户信息错误");
    }
    $scope.disList = [
        { title: "显示5条", value: 5 },
        { title: "显示10条", value: 10 },
        { title: "显示20条", value: 20 },
        { title: "显示50条", value: 50 },
        { title: "显示100条", value: 100 },
    ]
    $scope.totCount = 20;
    $scope.pauseFlag = false;
    var mqttClient = mqttClientInit($location.host());
    //mqttConnect(mqttClient, pubTopic, subTopic);
    $http.get("/Service/gsm/getGateways/?user=" + userName)
        .then(function (result) {
            $scope.gateways = result.data;
            if ($scope.gateways.length > 0){
                $scope.toggle($scope.gateways[0]);            
                $timeout(timer, timeTick);
            }
        });
    $scope.toggle = function (item) {
        if ($scope.currentGateway == item || item == null || typeof (item) == "undefined") {
            return;
        }
        $scope.currentGateway = item;        
        $scope.frames = [];
        // $http.get("/Service/gsw/getServerIP/?uuid=" + $scope.currentGateway.UUID + "&user=" + userName)
        //     .then(function (result) {});
        // $http.get("/Service/gsw/getServerIP/?uuid=" + $scope.currentGateway.UUID)
        //     .then(function (result) {
        //         //待替换，换成携带用户名向后端请求，后端以用户名为key启动线程，每个用户名只用一个发布订阅，并作为生产者提供帧，这里启动秒定时器轮询。
        //         $scope.serverIP = result.data.replace(/[ \r\n]/g,"");
        //         if($scope.serverIP != serverIP){
        //             serverIP = $scope.serverIP;
        //             if(serverIP == "127.0.0.1" || serverIP == "localhost" || serverIP == "0.0.0.0"){
        //                 mqttClient = mqttClientInit($location.host());
        //             }else{
        //                 mqttClient = mqttClientInit(serverIP);
        //             }
        //         }
        //     });
        // mqttDisconnect(mqttClient,pubTopic,subTopic);
        // pubTopic = $scope.currentGateway.PubTopic;
        // subTopic = $scope.currentGateway.SubTopic;
        // $scope.frames = [];
        // mqttConnect(mqttClient, pubTopic, subTopic);
    };
    $scope.frames = [];
    function mqttClientInit(ip) {
        client = new Paho.Client(ip, Number(8083), "WebClient");//建立客户端实例
        client.onConnectionLost = onConnectionLost;
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("连接已断开 onConnectionLost:" + responseObject.errorMessage);
                client.connect({ onSuccess: onConnect });//连接服务器并注册连接成功处理事件
            }
        }
        function onConnect() {   // 连接成功的回调函数
            mqttConnect(client, $scope.currentGateway.PubTopic, $scope.currentGateway.SubTopic);
        }
        //接收消息
        client.onMessageArrived = onMessageArrived;//注册消息接收处理事件
        function onMessageArrived(message) {
            if ($scope.pauseFlag) {
                return;
            }
            //console.log("收到消息:"+message.payloadString);
            var now = new Date();
            var nowStr = "" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds()
            if(message.payloadBytes  != null && typeof (message.payloadBytes) == "undefined" && message.payloadBytes.length > 0){
                if(message.payloadBytes[0] == '{' || message.payloadBytes[0] == '['){
                    str = "";
                    for(payloadi=0;payloadi<message.payloadBytes.length;payloadi++){
                        str += String.fromCharCode(message.payloadBytes[payloadi]);
                    }
                    //str = message.payloadBytes;
                } else{
                    str = bytesToStrBy16(message.payloadBytes);
                }
            } 
            str = bytesToStrBy16(message.payloadBytes);
            if (message.topic == pubTopic) {
                $scope.frames.unshift({
                    direct: "tx",
                    time: nowStr,
                    frame: str
                });
            }
            else if (message.topic == subTopic) {
                $scope.frames.unshift({
                    direct: "rx",
                    time: nowStr,
                    frame: str
                });
            }
            if ($scope.frames.length > $scope.totCount) {
                $scope.frames.splice($scope.totCount, $scope.frames.length - $scope.totCount)
            }
            if($route.current.loadedTemplateUrl != "views/gateway_watcher.html"){
                mqttDisconnect(client,$scope.currentGateway.PubTopic,$scope.currentGateway.SubTopic);
                return;
            }; 
            $scope.$apply();
            console.log(str);
        }
        return client
    }
    function bytesToStrBy16(bytes) {
        str = "";
        for (var i = 0; i < bytes.length; i++) {
            s = bytes[i].toString(16);
            if (s.length == 1)
                s = "0" + s;
            str = str + " 0x" + s;
        }
        return str;
    }
    function mqttConnect(client, pubTopic, subTopic) {
        mqttDisconnect(client, pubTopic, subTopic)
        try {
            client.connect({ onSuccess: onConnect });//连接服务器并注册连接成功处理事件
            function onConnect() {   // 连接成功的回调函数
                mqttClient.subscribe(pubTopic);//订阅主题
                mqttClient.subscribe(subTopic);//订阅主题
            }
        } catch (err) {
            console.info(err);
            //document.getElementById("demo").innerHTML = err.message;
        }
    }
    function mqttDisconnect(client, pubTopic, subTopic) {
        try {
            client.unsubscribe(pubTopic);
            client.unsubscribe(subTopic);
            client.disconnect();
        } catch (err) {
            console.info(err);
            //document.getElementById("demo").innerHTML = err.message;
        }
    }
}]);